package com.example.springcloudgateway.gatewayconfig.filters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.Objects;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

public class TestFilter implements GatewayFilter, Ordered {
    private Logger logger = LoggerFactory.getLogger(TestFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        System.out.println(req.getMethod());
        if ("GET".equalsIgnoreCase(req.getMethod().name())) {
            int result = doGet(exchange);
            if (result == 2) {
                return chain.filter(exchange.mutate().request(req).build()).then(Mono.fromRunnable(() -> {
                    //请求完成回调方法 可以再此完成计算请求耗时等操作
                    logger.info("请求完成，正在回调");
                }));
            }
            return chain.filter(exchange);
        } else {
            logger.info("POST请求暂未实现");
            return chain.filter(exchange);
        }
    }

    private int doGet(ServerWebExchange exchange) {
        ServerHttpRequest req = exchange.getRequest();
        String testParamValue = req.getQueryParams().getFirst("roomNo");
        //ReadBodyPredicateFactory 对象在路由定位器中已经缓存了请求参数，这里直接取就可以
        exchange.getAttributes().entrySet().forEach(entry -> System.out.println(entry.getKey() + "---" + entry.getValue()));
        Map<String, Object> attributes = exchange.getAttributes();
        if (attributes.isEmpty()) {
            logger.info("参数为空，直接跳过");
            return 0;
        }
        //随便写了个规则来改变路由地址
        if (Objects.equals(testParamValue, "101")) {
            logger.info("GET请求达到要求");
            exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, "111111111111111");
            return 2;

        } else {
            logger.info("不符合要求，直接通过");
            return 1;
        }
    }

    private void doPost() {

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
